﻿using FieldTools.Client.Command;
using FieldTools.Client.Model.Window;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FieldTools.Util;
using FieldTools.Client.Tools;
using System.Text.RegularExpressions;
using System.IO;
using FieldTools.Util.Helper;
using FieldTools.Client.View;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Wpf;
using FieldTools.Client.View.Window;

namespace FieldTools.Client.ViewModel.Window
{
    /// <summary>
    /// 微信工具视图模型
    /// </summary>
    public class WeChatViewModel : NotificationObject, ISingletonDependency
    {
        /// <summary>
        /// 
        /// </summary>
        public WeChatViewModel()
        {
            //LogHelper.WriteLog("打开WeChat工具");
            obj = CacheHelper.GetOrSetCache("WeChatModel", new WeChatModel()
            {
                Url = "",
                TextTag = false,
                PicTag = false,
                PdfTag = false
            });
        }

        #region 实体
        WeChatModel obj = new();
        /// <summary>
        /// 公众号文章url
        /// </summary>
        public string? Url
        {
            get { return obj.Url; }
            set { obj.Url = value; CacheHelper.SetCache("WeChatModel", obj); this.RaisePropertyChanged(nameof(Url)); }
        }

        /// <summary>
        /// 导出为文本的标记
        /// </summary>
        public bool? TextTag
        {
            get { return obj.TextTag; }
            set { obj.TextTag = value; CacheHelper.SetCache("WeChatModel", obj); this.RaisePropertyChanged(nameof(TextTag)); }
        }

        /// <summary>
        /// 导出为图片的标记
        /// </summary>
        public bool? PicTag
        {
            get { return obj.PicTag; }
            set { obj.PicTag = value; CacheHelper.SetCache("WeChatModel", obj); this.RaisePropertyChanged(nameof(PicTag)); }
        }

        /// <summary>
        /// 导出为pdf标记
        /// </summary>
        public bool? PdfTag
        {
            get { return obj.PdfTag; }
            set { obj.PdfTag = value; CacheHelper.SetCache("WeChatModel", obj); this.RaisePropertyChanged(nameof(PdfTag)); }
        }

        /// <summary>
        /// 源码
        /// </summary>
        public string HtmlDoc { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 作者
        /// </summary>
        public string Author { get; set; }
        private bool isLoading = false;
        /// <summary>
        /// 是否加载中
        /// </summary>
        public bool IsLoading
        {
            get { return isLoading; }
            set { isLoading = value; this.RaisePropertyChanged(nameof(IsLoading)); }
        }

        #endregion

        #region 事件
        private BaseCommand? execute;
        /// <summary>
        /// 执行解析
        /// </summary>
        public BaseCommand Execute
        {
            get
            {
                if (execute == null)
                {
                    execute = new BaseCommand(new Action<object>(async o =>
                    {
                        if (!string.IsNullOrEmpty(Url))
                        {
                            if (TextTag == true)ExportText();
                            if (PicTag == true)ExportPic();
                            if (PdfTag == true)await ExportPdf();
                        }
                    }));
                }
                return execute;
            }
        }

        private BaseCommand? preview;
        /// <summary>
        /// 预览
        /// </summary>
        public BaseCommand Preview
        {
            get
            {
                if (preview == null)
                {
                    preview = new BaseCommand(new Action<object>(o =>
                    {
                        if (!string.IsNullOrEmpty(Url))
                        {
                            //WebViewWindow webViewWindow = new(Url);
                            //webViewWindow.Show();
                            new WebViewWindow(Url).Show();
                        }
                    }));
                }
                return preview;
            }
        }

        #endregion

        #region 方法
        /// <summary>
        /// 导出文本
        /// </summary>
        public void ExportText()
        {
            if (string.IsNullOrEmpty(Url)) return;
            SourceInit();
            var textHtml = XmlHelper.GetElementByAngleSharp(HtmlDoc, "#js_content");
            if(textHtml != null)
            {
                IsLoading = true;
                try
                {
                    string text = textHtml.TextContent.Trim();
                    //while (true)
                    //{
                    //    if (text.Contains("\r\n\r\n"))
                    //    {
                    //        text = text.Replace("\r\n\r\n", "\r\n");
                    //    }
                    //    else
                    //    {
                    //        break;
                    //    }
                    //}
                    var savePath = $"WeChatTool/Text/";
                    if (!Directory.Exists(savePath))Directory.CreateDirectory(savePath);
                    using StreamWriter file = new($"{savePath}/{Title}-{Author}.txt");
                    file.Write(text);
                    IsLoading = false;
                    MessageBox.Show($"文本导出成功，位于{savePath}目录内");
                }
                catch (Exception ex)
                {
                    IsLoading = false;
                    //LogHelper.WriteLog("保存微信公众号文本失败：", ex);
                    MessageBox.Show("保存微信公众号文本失败，具体原因请查询日志");
                }
            }

        }
        /// <summary>
        /// 导出图片
        /// </summary>
        public void ExportPic()
        {
            if (string.IsNullOrEmpty(Url)) return;
            SourceInit();
            var ss = XmlHelper.GetElementsByAngleSharp(HtmlDoc, "img");
            var savePath = $"WeChatTool/Pic/{Title}-{Author}/";
            if (ss!=null && ss.Any())
            {
                IsLoading = true;
                bool errTag = false;
                var attributes = "data-src";
                for(int i = 0; i < ss.Count(); i++)
                {
                    var item = ss[i];
                    var src = item.Attributes[attributes]?.Value;
                    if(src!=null && src.IsNetResourcesPic())
                    {
                        try
                        {
                            if (!Directory.Exists(savePath))Directory.CreateDirectory(savePath);
                            var suf = src.GetNetResourcesSuffix();
                            src.DownloadFile($"{savePath}图片{i}.{suf}");
                        }
                        catch (Exception ex)
                        {
                            errTag = true;
                            //LogHelper.WriteLog("保存微信文章图片失败", ex);
                        }
                    }
                }
                IsLoading = false;
                MessageBox.Show($"图片下载完成，位于{savePath}目录内"+ (errTag ? ",可能有部分图片下载失败，请查询日志！！！" : ""));
            }
        }
        /// <summary>
        /// 导出pdf
        /// </summary>
        public async Task ExportPdf()
        {
            if (string.IsNullOrEmpty(Url)) return;
            SourceInit();
            var savePath = Directory.GetCurrentDirectory()+ $"/WeChatTool/PDF/";
            if (!Directory.Exists(savePath))Directory.CreateDirectory(savePath);
            WebViewWindow webView = new(Url);
            try
            {
                IsLoading = true;
                //PDFHelper.SavaPdfDefault(HtmlDoc, $"{savePath}{Title}-{Author}.pdf");
                webView.Show();
                webView.Hide();
                if (File.Exists($"{savePath}{Title}-{Author}.pdf")) File.Delete($"{savePath}{Title}-{Author}.pdf");
                bool res = false;
                if (webView.webView.CoreWebView2 == null)
                {
                    await webView.webView.EnsureCoreWebView2Async();
                }
                webView.webView.CoreWebView2.ProcessFailed += (sender, args) =>
                {
                    MessageBox.Show($"窗口加载出错");

                };
                webView.webView.NavigationCompleted += async (sender, args) =>
                {
                    res = await ((WebView2)sender).CoreWebView2?.PrintToPdfAsync($"{savePath}{Title}-{Author}.pdf");
                    if (res)
                    {
                        IsLoading = false;
                        webView.Close();
                        MessageBox.Show($"pdf导出成功，位于{savePath}目录内");
                    }
                    else
                    {
                        IsLoading = false;
                        webView.Close();
                        MessageBox.Show("pdf导出失败000");
                    }
                };
                //webView.Close();

            }
            catch (Exception ex)
            {
                //LogHelper.WriteLog("导出公众号文章为pdf失败", ex);
                webView.Close();
                IsLoading = false;
                MessageBox.Show("pdf导出失败，具体原因请查询日志");
            }
        }


        /// <summary>
        /// 初始化基础属性
        /// </summary>
        public void SourceInit()
        {
            if(string.IsNullOrEmpty(Url)) return;
            HtmlDoc = XmlHelper.GetHtmlByHttpWebRequest(Url);
            var titleHtml = XmlHelper.GetElementByAngleSharp(HtmlDoc, "h1");
            Title = titleHtml == null ? "未知标题" : titleHtml.InnerHtml.Trim();
            var authorHtml = XmlHelper.GetElementByAngleSharp(HtmlDoc, "#profileBt > a");
            Author = authorHtml == null ? "未知作者" : authorHtml.InnerHtml.Trim();
        }
        #endregion
    }
}
